var express = require("express");
var router = express.Router();

let { User } = require("../models//index");

/* GET users listing. */

// localhost:3000/users/
router.get("/", function (req, res, next) {
  res.send("respond with a resource");
});

// localhost:3000/users/a
router.get("/a", function (req, res, next) {
  res.send("a get");
});

router.post("/a", function (req, res, next) {
  res.send("a post");
});
router.put("/a", function (req, res, next) {
  res.send("a put");
});
router.delete("/a", function (req, res, next) {
  res.send("a delete");
});

// 注册和登录
let jwt = require("jsonwebtoken");
//   /users/login  post 请求-- username 和password
router.post("/login", async function (req, res) {
  console.log(req.body);
  let username = req.body.username;
  let password = req.body.password;

  //数据库中查询 用户名密码是否存在
  let u = await User.findOne(req.body);
  console.log(u);

  // 验证用户名和密码 数据库中验证
  if (u) {
    //服务器生成token 发给前端
    jwt.sign(
      { username: u.username, id: u._id },
      "zz123",
      {
        expiresIn: "30d",
      },
      function (err, token) {
        console.log(token);
        //生成token 成功
        res.json({
          code: 1,
          data: token,
          msg: "登录成功",
        });
      }
    );
  } else {
    // 返回json数据
    res.json({
      code: 0,
      msg: "请检查用户名或者密码",
    });
  }
});

router.post("/reg", async function (req, res) {
  console.log(req.body.username);
  console.log(req.body.password);

  let user = new User(req.body);
  let r = await user.save();
  console.log(r);
  // 插入数据库
  res.json({ code: 1, msg: "注册接口" });
});

module.exports = router;
